package com.tiger.angrybirds;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.tiger.angrybirds.MusicPlayServic.MyBinder;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class MainActivity extends BaseActivity implements ServiceConnection {
	private ListView contactList;
	private List<Music> infos;
	private ContactAdapter adapter;
	Intent serviceIntent = null;
	Bundle bundle = new Bundle();
	private String MusicPlayServic = "com.tiger.angrybirds.MusicPlayServic";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.menu);
		serviceIntent = new Intent();
		serviceIntent.setAction(MusicPlayServic);
		this.bindService(serviceIntent, this, BIND_AUTO_CREATE);
		// 广告根据时间加载
		DateFormat df = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date();
		long curDate = Long.parseLong(df.format(date));
		if (curDate >= 20110705) {
			CommonUtil.setAdView(this, this);
		}
		initView();
		handler.sendEmptyMessage(1);
	}

	private void initView() {
		adapter = new ContactAdapter(this);
		contactList = (ListView) this.findViewById(R.id.menu_list);
		contactList.setAdapter(adapter);
		contactList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View item,
					int position, long itemId) {
				ContactInfo info = (ContactInfo) item.getTag();
				if (info != null) {
					bundle.putInt("curId", position);
					Message msg = new Message();
					msg.setData(bundle);
					msg.what = 2;
					handler.dispatchMessage(msg);
					stopMusicPlay(info.id);
					startMusicPlay(info.id);
				}
			}
		});
		contactList.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View item,
					int position, long itemId) {
				// TODO Auto-generated method stub
				final ContactInfo info = (ContactInfo) item.getTag();
				new AlertDialog.Builder(MainActivity.this).setTitle(null)
						.setIcon(android.R.drawable.ic_dialog_info)
						.setSingleChoiceItems(
								MainActivity.this.getResources()
										.getStringArray(R.array.option_menu),
								3, new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
										switch (which) {
										case 0:
											if (CommonUtil.setCallRing(
													MainActivity.this,
													info.musicname.getText()
															.toString(),
													CommonUtil.rawIds[info.id])) {
												handler.sendEmptyMessage(3);
											} else {
												handler.sendEmptyMessage(4);
											}
											break;
										case 1:
											if (CommonUtil.setSmsRing(
													MainActivity.this,
													info.musicname.getText()
															.toString(),
													CommonUtil.rawIds[info.id])) {
												handler.sendEmptyMessage(3);
											} else {
												handler.sendEmptyMessage(4);
											}
											break;
										case 2:
											if (CommonUtil.setTimeRing(
													MainActivity.this,
													info.musicname.getText()
															.toString(),
													CommonUtil.rawIds[info.id])) {
												handler.sendEmptyMessage(3);
											} else {
												handler.sendEmptyMessage(4);
											}
											break;
										default:
											break;
										}

									}
								}).setNegativeButton("取消", null).show();
				return false;
			}

		});
	}

	private void startMusicPlay(int id) {
		bundle.putInt("musicId", id);
		serviceIntent.putExtras(bundle);
		this.startService(serviceIntent);

	}

	private void stopMusicPlay(int id) {
		bundle.putInt("musicId", id);
		serviceIntent.putExtras(bundle);
		this.stopService(serviceIntent);
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				infos = CommonUtil.getMusicmenu(MainActivity.this);
				adapter.notifyDataSetChanged();
				break;
			case 2:
				Bundle b = msg.getData();
				int curId = b.getInt("curId");
				for (int i = 0; i < infos.size(); i++) {
					if (i == curId) {
						infos.get(i).setVisible(true);
					} else {
						infos.get(i).setVisible(false);
					}
				}
				adapter.notifyDataSetChanged();
				break;
			case 3:
				Toast.makeText(
						MainActivity.this,
						"设置成功",
						Toast.LENGTH_SHORT)
						.show();
				break;
			case 4:
				Toast.makeText(
						MainActivity.this,
						"设置失败",
						Toast.LENGTH_SHORT)
						.show();
				break;
			}
		}
	};

	class ContactInfo {
		public TextView musicname;
		public ImageView play;
		public int id;
	}

	public class ContactAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public ContactAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if (infos == null)
				return 0;
			return infos.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ContactInfo holder = null;
			if (convertView == null) {
				holder = new ContactInfo();
				convertView = mInflater.inflate(R.layout.menu_item, null);
				holder.musicname = (TextView) convertView
						.findViewById(R.id.username);
				holder.play = (ImageView) convertView.findViewById(R.id.play);
			} else {
				holder = (ContactInfo) convertView.getTag();
			}

			if (infos != null) {
				holder.musicname.setText(infos.get(position).getName());
				holder.id = infos.get(position).getId();
				if (infos.get(position).isVisible()) {
					holder.play.setVisibility(View.VISIBLE);
				} else {
					holder.play.setVisibility(View.GONE);
				}
			}
			convertView.setTag(holder);
			return convertView;
		}

	}

	/**
	 * 设置铃声之后的回调函数
	 * 
	 * @Override protected void onActivityResult(int requestCode, int
	 *           resultCode, Intent data) { super.onActivityResult(requestCode,
	 *           resultCode, data); Log.i("zm", "resultCode:"+resultCode); if
	 *           (resultCode != RESULT_OK) { return; } else { // 得到我们选择的铃声 Uri
	 *           uri = data
	 *           .getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
	 *           Log.i("zm", "uri:"+uri.toString()); if (uri != null) { switch
	 *           (requestCode) { case 0:
	 *           RingtoneManager.setActualDefaultRingtoneUri(this,
	 *           RingtoneManager.TYPE_RINGTONE, uri); break; case 1:
	 *           RingtoneManager.setActualDefaultRingtoneUri(this,
	 *           RingtoneManager.TYPE_ALARM, uri); break; case 2:
	 *           RingtoneManager.setActualDefaultRingtoneUri(this,
	 *           RingtoneManager.TYPE_NOTIFICATION, uri); break; default: break;
	 *           } }
	 * 
	 *           } }
	 */
	MyBinder serviceBinder;
	MusicPlayServic mService;

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		// Log.i("zm", "onServiceConnected");
		// TODO Auto-generated method stub
		if (name.getShortClassName().endsWith("MusicPlayServic")) {
			try {
				this.serviceBinder = serviceBinder;
				mService = ((MusicPlayServic.MyBinder) serviceBinder)
						.getService();
				// mTracker = mService.mConfiguration.mTracker;
			} catch (Exception e) {
			}

		}
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
		// TODO Auto-generated method stub
		// Log.i("zm", "onServiceDisconnected");
	}
}